import { useEffect, useState } from 'react';
import { Card, Button, Input, message, Row, Col, Tag, Pagination, Skeleton, Empty } from 'antd';
import { ShoppingCartOutlined, SearchOutlined } from '@ant-design/icons';
import { addGoods, getGoodsList } from '@/api/shop';
import useUserInfoStore from '@/store/userInfoStore';

interface Product {
  id: number;
  publish_id: number;
  goods_name: string;
  goods_price: number;
  img: string;
  description: string;
  origin: string;
  created_time: string;
  tags?: string[]; // 保留 tags 作为可选属性，用于显示商品标签
}

/**
 * 商城页面
 * @returns
 */
const Business = () => {
  const { userInfo, token } = useUserInfoStore();
  const [searchText, setSearchText] = useState('');
  const [products, setProducts] = useState<Product[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(8);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);

  // 获取商品列表数据
  const fetchProducts = async (page: number, limit: number) => {
    try {
      setLoading(true);
      const res = await getGoodsList({ page, limit });
      setProducts(res.data.list);
      setTotal(res.data.total);
    } catch (e: any) {
      message.error('获取商品列表失败' + e.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // 请求数据
    fetchProducts(currentPage, pageSize);
  }, [currentPage, pageSize]);

  const handleAddToCart = async (product: Product) => {
    if (!userInfo.id || !token) {
      message.warning('请先登录');
      return;
    }
    const res = await addGoods({
      goods_id: product.id,
      goods_name: product.goods_name,
      goods_price: product.goods_price,
      goods_count: 1,
      img: product.img,
    });
    if (res.code === 200) {
      message.success(`已将 ${product.goods_name} 加入购物车`);
    } else {
      message.error(res.message);
    }
  };

  // 处理分页变化
  const handlePageChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
    // 平滑滚动到顶部
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // 搜索过滤
  const filteredProducts = searchText
    ? products.filter(
        (product) =>
          product.goods_name.toLowerCase().includes(searchText.toLowerCase()) ||
          product.description.toLowerCase().includes(searchText.toLowerCase())
      )
    : products;

  // 生成占位商品列表
  const placeholderProducts = loading
    ? Array(pageSize)
        .fill(null)
        .map((_, index) => ({ ...products[0], id: index }))
    : [];

  // 商品卡片组件
  const ProductCard = ({ product, loading }: { product: Product; loading: boolean }) => (
    <Card
      hoverable
      className="h-[420px]"
      cover={
        loading ? (
          <Skeleton.Image
            className="!h-48 !w-full"
            active
          />
        ) : (
          <div className="h-48 overflow-hidden bg-gray-100">
            <img
              alt={product.goods_name}
              src={product.img}
              className="w-full h-full object-cover"
              loading="lazy"
            />
          </div>
        )
      }
    >
      {loading ? (
        <Skeleton
          active
          paragraph={{ rows: 3 }}
        />
      ) : (
        <>
          <div className="mb-2 min-h-[28px]">
            {product.tags?.map((tag, index) => (
              <Tag
                key={index}
                color={
                  tag.includes('特惠') || tag.includes('特价')
                    ? 'red'
                    : tag.includes('新品')
                    ? 'blue'
                    : 'green'
                }
                className="mr-1 mb-1"
              >
                {tag}
              </Tag>
            ))}
          </div>
          <h3 className="text-lg font-medium text-gray-800 mb-1 truncate">{product.goods_name}</h3>
          <p className="text-gray-500 text-xs mb-1">产地：{product.origin}</p>
          <p className="text-gray-600 text-sm mb-3 line-clamp-2 min-h-[40px]">
            {product.description}
          </p>
          <div className="flex items-center justify-between mt-auto">
            <span className="text-lg font-semibold text-emerald-600">
              ¥{product.goods_price.toFixed(2)}
            </span>
            <Button
              type="primary"
              icon={<ShoppingCartOutlined />}
              onClick={() => handleAddToCart(product)}
              className="bg-emerald-600 hover:bg-emerald-700 border-none"
            >
              加入购物车
            </Button>
          </div>
        </>
      )}
    </Card>
  );

  return (
    <div className="h-full bg-gray-50 py-8 px-4">
      <div className="max-w-7xl mx-auto">
        {/* 搜索栏 */}
        <div className="mb-8">
          <h1 className="text-2xl font-bold text-gray-800 mb-4">野生菌商城</h1>
          <Input
            size="large"
            placeholder="搜索商品名称或描述..."
            prefix={<SearchOutlined className="text-gray-400" />}
            className="max-w-lg"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
          />
        </div>

        {/* 商品列表 */}
        {filteredProducts.length > 0 ? (
          <div className="min-h-[500px]">
            <Row gutter={[24, 24]}>
              {(loading ? placeholderProducts : filteredProducts).map((product) => (
                <Col
                  xs={24}
                  sm={12}
                  md={8}
                  lg={6}
                  key={product.id}
                  className="flex"
                >
                  <ProductCard
                    product={product}
                    loading={loading}
                  />
                </Col>
              ))}
            </Row>
          </div>
        ) : (
          <div className="min-h-[500px] flex justify-center items-center">
            <Empty description="当前分页下无对应商品" />
          </div>
        )}

        {/* 分页 */}
        {total > 0 && (
          <div className="flex justify-center mt-8 pb-10">
            <Pagination
              current={currentPage}
              pageSize={pageSize}
              total={total}
              onChange={handlePageChange}
              showSizeChanger
              showQuickJumper
              showTotal={(total) => `共 ${total} 件商品`}
              pageSizeOptions={['8', '16', '24', '32']}
              disabled={loading}
            />
          </div>
        )}
      </div>
    </div>
  );
};

export default Business;
